package com.ehotting.edsta.file.utils;

import cn.hutool.system.SystemUtil;
import com.ehotting.eaf.core.domain.ObjectItem;
import com.ehotting.eaf.core.utils.StringUtils;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import io.minio.messages.ObjectMetadata;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
public class MinioUtils {

    private final MinioClient minioClient;

    private final String bucketName;

    public MinioUtils(MinioClient minioClient, String bucketName) {
        this.minioClient = minioClient;
        this.bucketName = bucketName;
    }

    /**
     * description: 判断bucket是否存在，不存在则创建
     *
     * @return: void
     */
    public void existBucket(String name) {
        try {
            boolean exists = isExists(name);
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isExists(String name) throws Exception {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
    }

    /**
     * 创建存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * description: 上传文件
     *
     * @param multipartFile
     * @return: java.lang.String
     */
    public List<String> upload(MultipartFile[] multipartFile) {
        List<String> names = new ArrayList<>(multipartFile.length);
        for (MultipartFile file : multipartFile) {
            String fileName = file.getOriginalFilename();
            String[] split = fileName.split("\\.");
            if (split.length > 1) {
                fileName = split[0] + "_" + System.currentTimeMillis() + "." + split[1];
            } else {
                fileName = fileName + System.currentTimeMillis();
            }
            InputStream in = null;
            try {
                in = file.getInputStream();
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(in, in.available(), -1)
                        .contentType(file.getContentType())
                        .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            names.add(fileName);
        }
        return names;
    }

    public List<String> uploadByLocal(List<String> filepathList) {
        List<String> names = new ArrayList<>(filepathList.size());
        String osName = System.getProperty("os.name");
        for (String filepath : filepathList) {
            File file = new File(filepath);
            InputStream in = null;
            Path path = Paths.get(filepath);
            String fileName = path.subpath(0, path.getNameCount()).toString();
            if (osName.contains("Windows")) {
                fileName = fileName.replace("\\", "/");
            }
            try {
                Thread.sleep(500);
                in = Files.newInputStream(file.toPath());
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(in, in.available(), -1)
                        .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            names.add(fileName);
        }
        return names;
    }


    /**
     * description: 下载文件
     *
     * @param fileName
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
    public ResponseEntity<byte[]> download(String fileName) {
        ResponseEntity<byte[]> responseEntity;
        byte[] bytes = getBytesFromMinio(fileName);
        //封装返回值
        HttpHeaders headers = new HttpHeaders();
        try {
            headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        headers.setContentLength(bytes.length);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setAccessControlExposeHeaders(Arrays.asList("*"));
        responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

        return responseEntity;
    }

    public void downloadByHttp(String objectName, HttpServletResponse response) throws Exception {
        log.info("bucketName:{}, filename:{}", bucketName, objectName);
        // 调用getObjectInfo()方法获取文件的元数据信息
        StatObjectResponse metadata = getStateObject(objectName);
        InputStream in = null;

        String[] split = objectName.split("/");
        String filename = split[split.length - 1];
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.addHeader("Content-Length", "" + metadata.size());
        response.setContentType(metadata.contentType());
        byte[] buf = new byte[1024];
        int length = 0;
        OutputStream outputStream = response.getOutputStream();
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
            // 输出文件
            while ((length = in.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            // 关闭输出流
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public byte[] getBytesFromMinio(String fileName) {
        InputStream in = null;
        ByteArrayOutputStream out = null;

        try {
            log.info("bucketName:{}, filename:{}", bucketName, fileName);
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        assert out != null;
        if (out == null) {
            log.info("out is null");
        }
        return out.toByteArray();
    }

    /**
     * 查看文件对象
     *
     * @param bucketName 存储bucket名称
     * @return 存储bucket内文件对象信息
     */
    public List<ObjectItem> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<ObjectItem> objectItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                ObjectItem objectItem = new ObjectItem();
                objectItem.setObjectName(item.objectName());
                objectItem.setSize(item.size());
                objectItems.add(objectItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectItems;
    }

    /**
     * 批量删除文件对象
     *
     * @param bucketName 存储bucket名称
     * @param objects    对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        return results;
    }

    /**
     * @method: getPreviewFileUrl
     * @description: 获取带时间的过期链接
     * @author: WuChang
     * @date: 2022/12/19 2:36 PM
     */
    public String getPreviewFileUrl(String bucketName, String fileName) {
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .method(Method.GET)
                .expiry(30, TimeUnit.SECONDS)
                .build();
        String objectUrl = null;
        try {
            objectUrl = minioClient.getPresignedObjectUrl(build);
        } catch (ErrorResponseException | InsufficientDataException
                 | InternalException | InvalidKeyException | InvalidResponseException
                 | IOException | NoSuchAlgorithmException
                 | XmlParserException | ServerException e) {
            e.printStackTrace();
        }
        return objectUrl;
    }

    /**
     * 权限设置为读权限
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public void updateBucketPolicy(String bucketName, String policy) throws Exception {
        if (!isExists(bucketName)) {
            throw new Exception("bucket不存在");
        }
        if (StringUtils.isEmpty(policy)) {
            throw new Exception("策略不能为空");
        }
        try {
            switch (policy) {
                case "R":
                    policy = readonlyPolicy().toString();
                    break;
                case "W":
                    policy = writeonlyPolicy().toString();
                    break;
                case "RW":
                    policy = readwritePolicy().toString();
                    break;
                default:
                    throw new Exception("无对应策略");
            }
            minioClient.setBucketPolicy(SetBucketPolicyArgs
                    .builder().bucket(bucketName).config(policy).build());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Minio服务未知错误");
        }
    }


    /**
     * 仅读策略
     *
     * @return
     */
    private StringBuilder readonlyPolicy() {
        StringBuilder builder = new StringBuilder();
        builder.append("{\n" +
                "    \"Version\": \"2012-10-17\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Sid\":\"PublicRead\",\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": \"*\",\n" +
                "            \"Action\": [\n" +
                "                \"s3:GetBucketLocation\",\n" +
                "                \"s3:GetObject\"\n" +
                "            ],\n" +
                "            \"Resource\": [\n" +
                "                \"arn:aws:s3:::*\"\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}");
        return builder;
    }


    /**
     * 仅写策略
     *
     * @return
     */
    private StringBuilder writeonlyPolicy() {
        StringBuilder builder = new StringBuilder();
        builder.append("{\n" +
                "    \"Version\": \"2012-10-17\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Sid\":\"PublicWrite\",\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": \"*\",\n" +
                "            \"Action\": [\n" +
                "                  \"s3:PutObject\"" +
                "            ],\n" +
                "            \"Resource\": [\n" +
                "                \"arn:aws:s3:::*\"\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}");
        return builder;
    }

    /**
     * 默认权限：读写策略
     *
     * @return
     */
    private StringBuilder readwritePolicy() {
        StringBuilder builder = new StringBuilder();
        builder.append("{\n" +
                "    \"Version\": \"2012-10-17\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Sid\":\"PublicReadWrite\",\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": \"*\",\n" +
                "            \"Action\": [\n" +
                "                \"s3:ListAllMyBuckets\",\n" +
                "                \"s3:ListBucket\",\n" +
                "                \"s3:GetBucketLocation\",\n" +
                "                \"s3:GetObject\",\n" +
                "                \"s3:PutObject\",\n" +
                "                \"s3:DeleteObject\"\n" +
                "            ],\n" +
                "            \"Resource\": [\n" +
                "                \"arn:aws:s3:::*\"\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}");
        return builder;
    }

    public StatObjectResponse getStateObject(String filename) throws Exception {
        return minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(filename).build());
    }

}